package com.hjimi.ski.utils;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created By 孙岩
 * on 2023/12/19
 */
public class DownLoadPool {
    private static final int THREAD_COUNT = 10;
    private Handler mHandler;
    private ExecutorService mThreadPool;

    public DownLoadPool(Handler handler) {
        this.mHandler = handler;
        this.mThreadPool = Executors.newFixedThreadPool(THREAD_COUNT);

    }
    // 计算总下载大小
    int totalSize = 0;
    public void downloadImages(final List<String> imageUrls, final List<String> outputPaths) {

        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {

                for (String imageUrl : imageUrls) {
                    URL url = null;
                    try {
                        url = new URL(imageUrl);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setConnectTimeout(60000); // 1 minute timeout
                        conn.setReadTimeout(60000); // 1 minute timeout
                        conn.setDoInput(true);
                        conn.connect();
                        totalSize += conn.getContentLength();  // 获取URL的大小并累加到totalSize
//                ProgressDialogManager.getInstance().getDialog(context).setmText(formetFileSize(totalSize));
                        Log.d("sunyan","总共=--------"+ formetFileSize(totalSize));

                        // 在后台线程中发送消息到主线程
                        Message message = Message.obtain();
                        message.what = 50; // 设置消息标识符为0
                        message.obj = formetFileSize(totalSize); // 设置消息对象为"你好"字符串
                        mHandler.sendMessage(message); // 发送消息到主线程

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        for (int i = 0; i < imageUrls.size(); i++) {
            final int index = i;
            mThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        URL imageUrl = new URL(imageUrls.get(index));
                        HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
                        conn.setConnectTimeout(60000); // 1 minute timeout
                        conn.setReadTimeout(60000); // 1 minute timeout
                        conn.setDoInput(true);
                        conn.connect();
                        int responseCode = conn.getResponseCode();
                        if (responseCode == 200) {
                            String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/Pic/app";
                            File dir1 = new File(filePath);
                            if (!dir1.exists()) {
                                dir1.mkdirs();
                            }

                            InputStream is = conn.getInputStream();
                            OutputStream os = new FileOutputStream(outputPaths.get(index));
                            byte[] buffer = new byte[1024];
                            int len;
                            int progress = 0; // 用于记录当前进度的变量
                            while ((len = is.read(buffer)) != -1) {
                                os.write(buffer, 0, len);
                                progress += len; // 更新进度值
                                // 在后台线程中发送消息到主线程
                                Message message = Message.obtain();
                                message.what = 100; // 设置消息标识符为0
                                message.obj = ((int) (progress * 1f / totalSize * 100)) + "";
                                mHandler.sendMessage(message); // 发送消息到主线程
                            }
                            os.close();
                            is.close();

                            // 在此处调用回调方法，将下载成功的结果传递给主线程
                            if(index==imageUrls.size()-1){
                                mHandler.obtainMessage(1).sendToTarget();
                            }
                        } else {
                            // 在此处调用回调方法，将下载失败的结果传递给主线程
                            mHandler.obtainMessage(2).sendToTarget();
                        }
                    } catch (FileNotFoundException e){
                        // 在后台线程中发送消息到主线程
                        Message message = Message.obtain();
                        message.what = 4; // 设置消息标识符为0
                        message.obj = imageUrls.get(index);
                        mHandler.sendMessage(message); // 发送消息到主线程
                    } catch (Exception e) {
                        if(e.getMessage()!=null){
                            if(e.getMessage().contains("No space left on device")){
                                // 处理存储空间不足的情况
                                mHandler.obtainMessage(3).sendToTarget();
                            }else{
                                e.printStackTrace();
                            }
                        }
                        Log.d("sunyan", e.toString());
                    }
                }
            });
        }
    }

    /**
     * 说明:文件大小格式化
     *
     * @param fileS
     * @return
     */
    public static String formetFileSize(int fileS) {// 转换文件大小
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

}
